import type { TBody, TParams } from '@/types';
import { createConfig, handleReqMiddleware } from '@/lib/api';
import type {
  IClientFile,
  IUploadMessageSendFile,
  IUploadPostTemplateFile,
} from '@/interfaces';

export const queryFile = (
  params?: TParams
): Promise<Response | IClientFile> => {
  const config = createConfig(params);
  return fetch(config.baseURL + `/file/${config.id}`, config).then(
    handleReqMiddleware
  );
};

export const queryUserFiles = (
  params?: TParams
): Promise<Response | IClientFile[]> => {
  const config = createConfig(params);
  return fetch(config.baseURL + '/file/user', config).then(handleReqMiddleware);
};

export const removeFile = (params: TBody<void>): Promise<Response | void> => {
  const config = createConfig(params, { method: 'DELETE' });
  return fetch(config.baseURL + `/file/${config.id}`, config).then(
    handleReqMiddleware
  );
};

export const uploadAvatarFile = (
  params: TBody<{
    file?: string | Blob;
    formData?: FormData;
    signal?: AbortSignal;
    onUploadProgress?: (progressEvent: ProgressEvent) => void;
  }>
): Promise<Response | void> => {
  const { file, signal } = params.data as any;
  const formData = new FormData();
  formData.append('file', file);

  const config = createConfig(params, {
    method: 'POST',
    body: formData as any,
    signal,
  });

  return fetch(config.baseURL + '/file/users/avatar', config).then(
    handleReqMiddleware
  );
};

export const uploadMessageSendFile = (
  params: TBody<{
    file?: string | Blob;
    formData?: FormData;
    signal?: AbortSignal;
    onUploadProgress?: (progressEvent: ProgressEvent) => void;
  }>
): Promise<Response | IUploadMessageSendFile> => {
  const { file, signal } = params.data as any;
  const formData = new FormData();
  formData.append('file', file);

  const config = createConfig(params, {
    method: 'POST',
    body: formData as any,
    signal,
  });
  return fetch(config.baseURL + '/file/messages/send', config).then(
    handleReqMiddleware
  );
};

export const uploadPostTemplateFile = (
  params: TBody<{
    file?: string | Blob;
    formData?: FormData;
    signal?: AbortSignal;
    onUploadProgress?: (progressEvent: ProgressEvent) => void;
  }>
): Promise<Response | IUploadPostTemplateFile> => {
  const { file, signal } = params.data as any;
  const formData = new FormData();
  formData.append('file', file);

  const config = createConfig(params, {
    method: 'POST',
    body: formData as any,
    signal,
  });
  return fetch(
    config.baseURL + `/templates/sections/${config.id}`,
    config
  ).then(handleReqMiddleware);
};
